package com.yangjian.exception;


import com.yangjian.comon.R;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.sql.SQLIntegrityConstraintViolationException;

@RestControllerAdvice
@ResponseBody
public class GlobalExceptionHandling {

    //捕获自定义异常
    @ExceptionHandler(CustomException.class)
    public R handlerCustomException(CustomException e) {
        //打印异常信息
        e.printStackTrace();
        //给前端提示一个异常
        return R.error(e.getMessage());
    }

    //运行时异常
    @ExceptionHandler(SQLIntegrityConstraintViolationException.class)
    public R handlerSQLException(SQLIntegrityConstraintViolationException e) {

        //打印异常信息
        e.printStackTrace();
        //获取异常信息
        String message = e.getMessage();

        //判断是不是唯一约束异常
        if (message.contains("Duplicate entry")) {

            return R.error(message.split(" ")[2] + "已存在");
            //message.split  :表示切割
        } else {

            return R.error("未知异常");
        }

    }

}
